<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2021/1/13
 * Time: 15:32
 */

namespace app\api\controller;


use pay\Ali;
use pay\Wxservicer;
use think\Db;

class Goods extends Base
{
    public $user_id; // 用户ID
    public $page; // 页码
    public $create_time;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status' => 301, 'msg' => $this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    
    /**
     * 商品分类---特惠商品
     * @return \think\response\Json
     */
    public function goodsCate(){
        // 特惠商城用户可以看到所有，其它用户只能看到礼包
        $userRule = $this->userRule($this->user_id);
        if($userRule == '2' || $userRule == '2,3'){
            $cate = Db::table('up_goods_cate')->where('gc_level', 1)->field('gc_id, gc_name')->select();
        }else{
            $cate = Db::table('up_goods_cate')->where('gc_id', 4)->field('gc_id, gc_name')->select();
        }

        if($cate){
            foreach($cate as $k => $v){
                $son = Db::table('up_goods_cate')->where('gc_pid', $v['gc_id'])->field('gc_id, gc_name')->select();
                if($son){
                    $cate[$k]['son'] = $son;
                }else{
                    $cate[$k]['son'] = [];
                }
            }
            return json(['status' => 200, 'msg' => $cate]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 商品搜索列表---特惠商品
     * @return \think\response\Json
     * keyword    搜索关键字
     * page       页码
     */
    public function searchKeyword(){
        $keyword = input('keyword');

        $where = [];
        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_th_rule, user_rule')->find();
        if(isset($keyword) && $keyword != ''){
            $where['goods_name'] = ['like', '%' . $keyword . '%'];
            if($user['user_rule'] == '1' || $user['user_rule'] == '3'){ // 非特惠商城用户
                $where['goods_first_cate'] = 4;
                $where['goods_th_rule'] = $user['user_th_rule'];
            }else{
                $where = "(goods_first_cate = 4 AND goods_th_rule = {$user['user_th_rule']}) OR goods_first_cate <> 4";
            }
        }else{
            if($user['user_rule'] == '1' || $user['user_rule'] == '3'){ // 非特惠商城用户
                $where['goods_first_cate'] = 4;
                $where['goods_th_rule'] = $user['user_th_rule'];
            }else{
                $where = "(goods_first_cate = 4 AND goods_th_rule = {$user['user_th_rule']}) OR goods_first_cate <> 4";
            }
        }

        $goods = $this->thGoods($where);
        if($goods){
            return json(['status' => 200, 'msg' => $goods]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }

    }

    /**
     * 商品搜索列表---特惠商品
     * @return \think\response\Json
     * gc_first_id    一级分类
     * gc_second_id   二级分类
     * page       页码
     */
    public function getGoodsByCate(){
        $first_cate_id = input('gc_first_id'); // 一级分类ID
        $second_cate_id = input('gc_second_id'); // 二级分类ID

        // 搜索条件需要区分特惠礼包角色
        $where = [];
        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_th_rule, user_rule')->find();
        if(isset($first_cate_id) && $first_cate_id != ''){
            $where['goods_first_cate'] = $first_cate_id;
            if($first_cate_id == 4){
                $where['goods_th_rule'] = $user['user_th_rule'];
            }
        }
        if(isset($second_cate_id) && $second_cate_id != ''){
            $where['goods_second_cate'] = ['LIKE', '%,' . $second_cate_id . ',%'];
            $fc_id = Db::table('up_goods_cate')->where('gc_id', $second_cate_id)->field('gc_pid')->find();
            if($fc_id['gc_pid'] == 4){
                $where['goods_th_rule'] = $user['user_th_rule'];
            }
        }

        $goods = $this->thGoods($where);
        if($goods){
            return json(['status' => 200, 'msg' => $goods]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }

    }
    
    /**
     * 商品列表---特惠商品----作废
     * @return \think\response\Json
     * page          页码
     * goods_type    1 花样青青   2 脖脸皮
     *
     */
    public function goodsList(){
        $goods_type = input('goods_type');
        $where['goods_type'] = $goods_type;
        
        $goods = $this->thGoods($where);
        if($goods){
            return json(['status' => 200, 'msg' => $goods]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 商品详情---特惠商品
     * @return \think\response\Json
     * goods_id     商品ID
     */
    public function goodsDetail(){
        $goods_id = input('goods_id');
        $detail = Db::table('up_goods')
            ->where('goods_id', $goods_id)
            ->field('goods_id, goods_name, goods_images, goods_price, goods_vip_price, goods_spec, goods_stock, 
            goods_sale_num, goods_content, goods_thumb, goods_is_show_sale_num, goods_is_show_stock, goods_first_cate')
            ->find();
        // 图片
        if($detail['goods_images']){
            $detail['goods_images'] = explode(',', $detail['goods_images']);
        }else{
            $detail['goods_images'] = [];
        }
        // 购物车数量
        $shop_car_num = $this->myThShopCar(1);
        $detail['shop_car_num'] = $shop_car_num;
        // 是否收藏
        $is_collect = Db::table('up_my_collect_goods')
            ->where('cg_user_id', $this->user_id)
            ->where('cg_goods_id', $goods_id)
            ->find();
        if($is_collect){
            $detail['collect'] = 1; // 已收藏
        }else{
            $detail['collect'] = 2; // 未收藏
        }
        return json(['status' => 200, 'msg' => $detail]);
    }

    /**
     * 特惠商品详情---用于H5
     * @return \think\response\Json
     * goods_id      商品详情
     */
    public function goodsDetailForH5(){
        header("Access-Control-Allow-Origin: *");
        $goods_id = input('goods_id');
        $detail = Db::table('up_goods')
            ->where('goods_id', $goods_id)
            ->field('goods_id, goods_name, goods_images, goods_spec, goods_content, goods_thumb')
            ->find();
        // 图片
        if($detail['goods_images']){
            $detail['goods_images'] = explode(',', $detail['goods_images']);
        }else{
            $detail['goods_images'] = [];
        }
        return json(['status' => 200, 'msg' => $detail]);
    }
    
    /**
     * 加入购物车---特惠商品
     * @return \think\response\Json
     * goods_id      商品ID
     * goods_num     购买的商品数量
     */
    public function addShopCar(){
        $goods_id = input('goods_id');
        $goods_num = input('goods_num'); // 数量

        $goods = Db::table('up_goods')
            ->where('goods_id', $goods_id)
            ->field('goods_stock, goods_first_cate')
            ->find();
        if($goods_num > $goods['goods_stock']) return json(['status' => 0, 'msg' => '库存不足']);

        if($goods['goods_first_cate'] == 4){ // 礼包分类
            return json(['status' => 0, 'msg' => '该类商品不可加入购物车']);
        }else{
            $userRule = $this->userRule($this->user_id);
            if($userRule == '1' || $userRule == '3') return json(['status' => 0, 'msg' => '权限不足']);
        }
        
        $in_shopcar = Db::table('up_shop_car')
            ->where('sc_user_id', $this->user_id)
            ->where('sc_goods_id', $goods_id)
            ->field('sc_goods_number, sc_id')
            ->find();
        if($in_shopcar){
            // 如果已有相同商品，则数量叠加
            $res = Db::table('up_shop_car')->where('sc_id', $in_shopcar['sc_id'])->setInc('sc_goods_number', $goods_num);
        }else{
            // 如果没有，则插入记录
            $insert = [
                'sc_user_id' => $this->user_id,
                'sc_goods_id' => $goods_id,
                'sc_goods_number' => $goods_num,
                'sc_time' => $this->create_time
            ];
            $res = Db::table('up_shop_car')->insert($insert);
        }
        if($res){
            return json(['status' => 200, 'msg' => '加入购物车成功']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }
    
    /**
     * 收藏/取消收藏
     * @return \think\response\Json
     * goods_id      商品ID
     */
    public function collect(){
        $goods_id = input('goods_id');
        
        $is_collect = Db::table('up_my_collect_goods')->where('cg_user_id', $this->user_id)->where('cg_goods_id', $goods_id)->field('cg_id')->find();
        if($is_collect){
            $res = Db::table('up_my_collect_goods')->delete($is_collect['cg_id']);
        }else{
            $insert = [
                'cg_user_id' => $this->user_id,
                'cg_goods_id' => $goods_id,
                'cg_time' => $this->create_time
            ];
            $res = Db::table('up_my_collect_goods')->insert($insert);
        }
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }
    
    /**
     * 我的购物车---特惠商品
     * @return \think\response\Json
     */
    public function shopCar(){
        $shopcar = $this->mytHShopCar(2);
        
        if($shopcar){
            return json(['status' => 200, 'msg' => $shopcar]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 删除购物车---特惠商品
     * @return \think\response\Json
     * sc_ids     购物车ID   逗号隔开
     */
    public function delShopCar(){
        $sc_ids = input('sc_ids');
        $res = Db::table('up_shop_car')->where('sc_id', 'IN', $sc_ids)->delete();
        if($res){
            return json(['status' => 200, 'msg' => '删除成功']);
        }else{
            return json(['status' => 0, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 购物车增加数量---特惠商品
     * @return \think\response\Json
     * sc_id     购物车ID
     */
    public function incNum(){
        $sc_id = input('sc_id');
        $car = Db::table('up_shop_car')
            ->join('up_goods', 'sc_goods_id = goods_id', 'LEFT')
            ->where('sc_id', $sc_id)
            ->field('sc_goods_number, goods_stock, goods_first_cate')
            ->find();
        if($car['sc_goods_number'] >= $car['goods_stock']) return json(['status' => 0, 'msg' => '超过最大库存']);
//        if($car['goods_first_cate'] == 4) return json(['status' => 0, 'msg' => '该类商品只可购买一件']);
        
        $res = Db::table('up_shop_car')->where('sc_id', $sc_id)->setInc('sc_goods_number');
        if($res){
            return json(['status' => 200, 'msg' => true]);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }
    
    /**
     * 减购物车商品数量---特惠商品
     * @return \think\response\Json
     * sc_id    购物车ID
     */
    public function decNum(){
        $sc_id = input('sc_id');
        $car = Db::table('up_shop_car')->where('sc_id', $sc_id)->field('sc_goods_number')->find();
        if($car['sc_goods_number'] <= 1) return json(['status' => 0, 'msg' => false]);
        $res = Db::table('up_shop_car')->where('sc_id', $sc_id)->setDec('sc_goods_number');
        if($res){
            return json(['status' => 200, 'msg' => true]);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }
    
    /**
     * 设置购物车商品数量---特惠商品
     * @return \think\response\Json
     * sc_id      购物车ID
     * num        商品数量
     */
    public function setNum(){
        $sc_id = input('sc_id');
        $num = input('num');
        $car = Db::table('up_shop_car')
            ->join('up_goods', 'sc_goods_id = goods_id', 'LEFT')
            ->where('sc_id', $sc_id)
            ->field('goods_stock, goods_first_cate')
            ->find();
        if($car['goods_stock'] < $num) return json(['status' => 0, 'msg' => '库存不足']);
//        if($car['goods_first_cate'] == 4) return json(['status' => 0, 'msg' => '该类商品只可购买一件']);

        $res = Db::table('up_shop_car')->where('sc_id', $sc_id)->setField('sc_goods_number', $num);
        if($res){
            return json(['status' => 200, 'msg' => true]);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }
    
    /**
     * 立即购买---特惠商品
     * @return \think\response\Json
     * goods_id     商品ID
     * goods_num    购买数量
     */
    public function nowBuyOneGoods(){
        $goods_id = input('goods_id');
        $goods_num = input('goods_num');

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);

        if($goods_num == 0) return json(['status' => 0, 'msg' => '购买的数量不能为0']);
        
        $goods = Db::table('up_goods')
            ->where('goods_id', $goods_id)
            ->field('goods_stock, goods_vip_price, goods_spec, goods_name, goods_thumb, goods_first_cate, goods_th_rule')
            ->find();

        if(!$goods) return json(['status' => 0, 'msg' => '购买的商品错误']);
        
        if($goods_num > $goods['goods_stock']) return json(['status' => 0, 'msg' => '库存不足']);

        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_rule, user_th_rule')->find();
        if($goods['goods_first_cate'] == 4){ // 礼包分类
            if($user['user_th_rule'] != $goods['goods_th_rule']) return json(['status' => 0, 'msg' => '购买权限不足']);
            if($goods_num > 1){
                return json(['status' => 0, 'msg' => '该商品只能购买一件']);
            }
            $hasBuy = Db::table('up_order_info')
                ->join('up_order', 'order_id = oi_order_id', 'LEFT')
                ->where(['oi_user_id' => $this->user_id, 'oi_goods_id' => $goods_id, 'order_is_pay' => 2])
                ->find();
            if($hasBuy) return json(['status' => 0, 'msg' => '该商品不可重复购买']);

            $order_type = 2;
            $order_goods_id = $goods_id;
            $order_th = $goods['goods_th_rule'];
        }else{
            if($user['user_rule'] == '1' || $user['user_rule'] == '3') return json(['status' => 0, 'msg' => '购买权限不足']);

            $order_type = 1;
            $order_goods_id = 0;
            $order_th = 0;
        }

        // 总价
        $total_price = $goods_num * $goods['goods_vip_price'];
        // 订单号
        $order_num = 'TH_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
    
        $order = [
            'order_user_id' => $this->user_id,
            'order_number' => $order_num,
            'order_total_price' => $total_price,
            'order_total_num' => $goods_num,
//            'order_addr_id' => $order_addr_id,
            'order_create_time' => $this->create_time,
            'order_type' => $order_type,
            'order_goods_id' => $order_goods_id,
            'order_th' => $order_th
        ];
        $field = 'addr_id, addr_user_name, addr_user_phone, addr_sheng, addr_shi, addr_qu, addr_address';

        $order_addr = Db::table('up_user_address')
            ->where('addr_user_id', $this->user_id)
            ->where('addr_from', 1)
            ->field($field)
            ->find();
        if(!$order_addr) return json(['status' => 111, 'msg' => false]);
        $order['order_addr_id'] = $order_addr['addr_id'];
        $order['order_sheng'] = $order_addr['addr_sheng'];
        $order['order_shi'] = $order_addr['addr_shi'];
        $order['order_qu'] = $order_addr['addr_qu'];
        $order['order_address'] = $order_addr['addr_address'];
        $order['order_receive_username'] = $order_addr['addr_user_name'];
        $order['order_receive_phone'] = $order_addr['addr_user_phone'];
        
        Db::startTrans();
        try{
            // 插入订单表
            $order_id = Db::table('up_order')->insertGetId($order);

            // 插入订单详情表
            $order_info = [
                'oi_order_id' => $order_id,
                'oi_goods_id' => $goods_id,
                'oi_user_id' => $this->user_id,
                'oi_goods_price' => $goods['goods_vip_price'],
                'oi_num' => $goods_num,
                'oi_goods_thumb' => $goods['goods_thumb'],
                'oi_goods_name' => $goods['goods_name'],
                'oi_goods_spec' => $goods['goods_spec']
            ];
            Db::table('up_order_info')->insert($order_info);

            // 减库存&增加销量
            Db::table('up_goods')->where('goods_id', $goods_id)->inc('goods_sale_num', $goods_num)->dec('goods_stock', $goods_num)->update();

            Db::commit();
            return json(['status' => 200, 'msg' => $order_id]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 提交订单页面展示---特惠商品
     * @return \think\response\Json
     * order_id    订单ID
     */
    public function showCommitOrder(){
        $order_id = input('order_id');

        // 订单
        $order = Db::table('up_order')
            ->join('up_u_user', 'user_id = order_user_id', 'LEFT')
            ->where('order_id', $order_id)
            ->field('order_total_price, order_total_num, user_recharge_balance, order_create_time')
            ->find();
        // 商品
        $goods = Db::table('up_order_info')
            ->where('oi_order_id', $order_id)
            ->field('oi_goods_id, oi_goods_price, oi_num, oi_goods_thumb, oi_goods_name, oi_goods_spec')
            ->select();
        // 快递
        $order['express'] = Db::table('up_about')->where('id', 7)->value('content');
        return json(['status' => 200, 'msg' => $order, 'goods' => $goods]);
    }
    
    /**
     * 提交立即购买订单---特惠商品
     * @return \think\response\Json
     * order_id      订单ID
     * order_addr_id    收货地址ID
     * order_remark     备注
     */
    public function commitOrder(){
        $order_id = input('order_id');
        $order_addr_id = input('order_addr_id');
        $order_remark = input('order_remark');
        $pay_type = input('pay_type') ? input('pay_type') : 1; // 1 积分   2 微信   3 支付宝

        $order = Db::table('up_order')
            ->join('up_u_user', 'user_id = order_user_id', 'LEFT')
            ->where('order_id', $order_id)
            ->field('order_total_price, user_recharge_balance, order_user_id, order_status, order_type, 
            order_goods_id, order_total_price, order_number, user_rule, user_th_rule')
            ->find();

        // 特惠礼包重复购买
        if($order['order_type'] == 2){
            $goods = Db::table('up_goods')->where('goods_id', $order['order_goods_id'])->field('goods_th_rule')->find();
            if($order['user_th_rule'] != $goods['goods_th_rule']) return json(['status' => 0, 'msg' => '购买权限不足']);

            $buyAlreadyPay = Db::table('up_order')
                ->where([
                    'order_user_id' => $this->user_id,
                    'order_is_pay' => 2,
                    'order_type' => 2,
                    'order_goods_id' => $order['order_goods_id']
                ])
                ->find();
            if($buyAlreadyPay) return json(['status' => 0, 'msg' => '该商品不可重复购买']);
        }else{
            if($order['user_rule'] == '1' || $order['user_rule'] == '3') return json(['status' => 0, 'msg' => '权限不足']);

            if($order['order_total_price'] > $order['user_recharge_balance']) return json(['status' => 222, 'msg' => '可用积分不足']);
        }

        $mchid = Db::table('up_mchid')->where(['mch_default' => 1, 'mch_status' => 1])->find();
        if(!$mchid) return json(['status' => 0, 'msg' => '暂无可收款账户，请联系客服']);

        if($pay_type == 1 || ($order['order_type'] == 2 && $order['order_total_price'] == 0)){
            $order_status = 2;
            $is_pay = 2;
        }else{
            $order_status = 1;
            $is_pay = 1;
        }
    
        $update = [
            'order_pay_type' => $pay_type,
            'order_remark' => $order_remark,
//            'order_addr_id' => $order_addr_id,
            'order_status' => $order_status,
            'order_is_pay' => $is_pay
        ];
        if($is_pay == 2){
            $update['order_pay_time'] = $this->create_time;
        }

        if(isset($order_addr_id) && $order_addr_id != ''){
            $address = Db::table('up_user_address')->where('addr_id', $order_addr_id)
                ->field('addr_id, addr_user_name, addr_user_phone, addr_sheng, addr_shi, addr_qu, addr_address')
                ->find();
            $update['order_addr_id'] = $order_addr_id;
            $update['order_sheng'] = $address['addr_sheng'];
            $update['order_shi'] = $address['addr_shi'];
            $update['order_qu'] = $address['addr_qu'];
            $update['order_address'] = $address['addr_address'];
            $update['order_receive_username'] = $address['addr_user_name'];
            $update['order_receive_phone'] = $address['addr_user_phone'];
        }
        
        if($order['order_status'] == 1){
            Db::startTrans();
            try{
                // 更新订单表
                Db::table('up_order')->where('order_id', $order_id)->update($update);

                if($order['order_type'] == 2){ // 礼包订单
                    if($order['order_total_price'] == 0){ // 直接完成支付
                        Db::commit();
                        return json(['status' => 202, 'msg' => $order_id, 'price' => $order['order_total_price']]);
                    }else{ // 微信/支付宝支付
                        if($pay_type == 2){
                            // 调起微信支付
                            $wxConfig = config('wechat_servicer');
                            $wxConfig['sub_mchid'] = $mchid['mch_code'];
                            $wx = new Wxservicer($wxConfig);
                            $return = $wx->WeChatPayReadyServicerV2($order['order_total_price'], $order['order_number'], '购买特惠礼包');
                        }else{
                            // 调起支付宝支付
                            $ali = new Ali(config('ali'));
                            $return = $ali->getParam($order['order_number'], $order['order_total_price'], '特惠礼包', '购买特惠礼包');
                        }
                        if($return['status'] == 200){
                            Db::commit();
                            return json(['status' => 200, 'msg' => $return['message'], 'order_id' => $order_id, 'price' => $order['order_total_price']]);
                        }else{
                            Db::rollback();
                            return json(['status' => 0, 'msg' => $return['message']]);
                        }
                    }
                }else{ // 积分支付
                    // 用于更新用户剩余积分的数组
//                    $update_price = $this->decPrice($order);
                    $update_price['user_recharge_balance'] = $order['user_recharge_balance'] - $order['order_total_price'];

                    // 更新用户余额
                    Db::table('up_u_user')->where('user_id', $order['order_user_id'])->update($update_price);

                    // 积分明细
                    $this->insertThInte($order['order_user_id'], 2, '购买商品-消费', $order['order_total_price'], $order['user_recharge_balance'], $order_id);

                    Db::commit();
                    return json(['status' => 200, 'msg' => $order_id, 'price' => $order['order_total_price'], 'sy_price' => $update_price['user_recharge_balance']]);
                }

            }catch(\Exception $e){
                Db::rollback();
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        }else{
            return json(['status' => 0, 'msg' => '请勿重复提交']);
        }
        
    }
    
    /**
     * 购物车提交订单---特惠商品
     * @return \think\response\Json
     * sc_ids     购物车ID，多个用逗号隔开
     */
    public function shopcarCommitOrder(){
        $sc_ids = input('sc_ids'); // 购物车ID,多个用逗号隔开

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);

        $userRule = $this->userRule($this->user_id);
        if($userRule == '1' || $userRule == '3') return json(['status' => 0, 'msg' => '权限不足']);

        $car = Db::table('up_shop_car')
            ->join('up_goods', 'sc_goods_id = goods_id', 'LEFT')
            ->where('sc_id', 'IN', $sc_ids)
            ->field('sc_goods_number, goods_vip_price, goods_stock, goods_name, goods_thumb, goods_spec, 
            goods_id, goods_status, goods_id')
            ->select();
        if(!$car) return json(['status' => 0, 'msg' => '所选商品不存在，请重新添加购物车']);
        
        $total_price = 0; // 商品总价
        $total_num = 0; // 订单商品总数
        $stock = ['flag' => 1, 'msg' => '']; // 用于判断某个商品异常
        $order_info = []; // 订单详情数组
        $order_num = 'TH_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT); // 订单号
        
        foreach($car as $k => $v){
            if($v['sc_goods_number'] < 1){
                $stock['flag'] = 2;
                $stock['msg'] = '商品' . $v['goods_name'] . '购买数量不可小于1';
                break;
            }
            if($v['goods_stock'] < $v['sc_goods_number']){
                $stock['flag'] = 2;
                $stock['msg'] = '商品' . $v['goods_name'] . '库存不足';
                break;
            }
            if($v['goods_status'] != 1){
                $stock['flag'] = 2;
                $stock['msg'] = '商品' . $v['goods_name'] . '状态异常，请重新选择商品';
                break;
            }

            $total_price += $v['goods_vip_price'] * $v['sc_goods_number'];
            $total_num += $v['sc_goods_number'];
            $order_info[$k] = [
                'oi_goods_id' => $v['goods_id'],
                'oi_user_id' => $this->user_id,
                'oi_goods_price' => $v['goods_vip_price'],
                'oi_num' => $v['sc_goods_number'],
                'oi_goods_thumb' => $v['goods_thumb'],
                'oi_goods_name' => $v['goods_name'],
                'oi_goods_spec' => $v['goods_spec']
            ];
        }
        if($stock['flag'] == 2) return json(['status' => 0, 'msg' => $stock['msg']]);
    
        $order = [
            'order_user_id' => $this->user_id,
            'order_number' => $order_num,
            'order_total_price' => $total_price,
            'order_total_num' => $total_num,
            'order_create_time' => $this->create_time
        ];
        // 直接使用注册时的收货地址，不需要选择
        $order_addr = Db::table('up_user_address')
            ->where('addr_user_id', $this->user_id)
            ->where('addr_from', 1)
            ->field('addr_id, addr_user_name, addr_user_phone, addr_sheng, addr_shi, addr_qu, addr_address')
            ->find();
        if($order_addr){
            $order['order_addr_id'] = $order_addr['addr_id'];
            $order['order_sheng'] = $order_addr['addr_sheng'];
            $order['order_shi'] = $order_addr['addr_shi'];
            $order['order_qu'] = $order_addr['addr_qu'];
            $order['order_address'] = $order_addr['addr_address'];
            $order['order_receive_username'] = $order_addr['addr_user_name'];
            $order['order_receive_phone'] = $order_addr['addr_user_phone'];
        }else{
            return json(['status' => 111, 'msg' => false]); // 先去添加收货地址
        }
        
        
        Db::startTrans();
        try{
            // 插入订单表
            $order_id = Db::table('up_order')->insertGetId($order);
            
            // 订单详情
            foreach($order_info as $kk => $vv){
                $order_info[$kk]['oi_order_id'] = $order_id;
            }
            Db::table('up_order_info')->insertAll($order_info);

            // 减库存&增加销量
            foreach($car as $ke => $vo){
                Db::table('up_goods')
                    ->where('goods_id', $vo['goods_id'])
                    ->inc('goods_sale_num', $vo['sc_goods_number'])
                    ->dec('goods_stock', $vo['sc_goods_number'])
                    ->update();
            }

            // 删除购物车
            Db::table('up_shop_car')->where('sc_id', 'IN', $sc_ids)->delete();
            Db::commit();
            return json(['status' => 200, 'msg' => $order_id]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 新增收货地址（花样青青商品专用）
     * @return \think\response\Json
     * addr_user_name     收货人
     * addr_user_phone    收货手机号
     * addr_sheng         省
     * addr_shi           市
     * addr_qu            区
     * addr_address       详细地址
     */
    public function createAddr(){
        $addr_user_name = input('addr_user_name');
        $addr_user_phone = input('addr_user_phone');
        $addr_sheng = input('addr_sheng');
        $addr_shi = input('addr_shi');
        $addr_qu = input('addr_qu');
        $addr_address = input('addr_address');
        
        $addr = [
            'addr_user_id' => $this->user_id,
            'addr_user_name' => $addr_user_name,
            'addr_user_phone' => $addr_user_phone,
            'addr_sheng' => $addr_sheng,
            'addr_shi' => $addr_shi,
            'addr_qu' => $addr_qu,
            'addr_address' => $addr_address,
            'addr_is_default' => 2,
            'addr_from' => 1,
            'addr_time' => $this->create_time
        ];
        $res = Db::table('up_user_address')->insert($addr);
        if($res){
            return json(['status' => 200, 'msg' => true]);
        }else{
            return json(['status' => 0, 'msg' => false]);
        }
    }
    
    //***************************  公共方法   *************************//
    /**
     * 特惠商品购物车
     * @param int $data_type   1 统计数量   2 列表
     * @return false|int|\PDOStatement|string|\think\Collection
     */
    private function mytHShopCar($data_type = 1){
        $where['sc_user_id'] = $this->user_id;

        $query = Db::table('up_shop_car')->where($where);
        if($data_type == 1){
            $data = $query->count();
        }else{
            $data = $query->join('up_goods', 'sc_goods_id = goods_id', 'LEFT')
                ->field('sc_id, goods_thumb, goods_name, goods_price, goods_vip_price, goods_spec, 
                goods_stock, sc_goods_number, sc_goods_id')
                ->order('sc_time desc')
                ->select();
        }
        return $data;
    }
    
    /**
     * 根据扣款顺序，生成用户剩余积分的更新数组
     * @param $order     订单信息
     * @return array
     */
    private function decPrice($order){
//        $update_price = [
//            'user_first_balance' => $order['user_first_balance'],
//            'user_huo_balance' => $order['user_huo_balance'],
//            'user_recharge_balance' => $order['user_recharge_balance']
//        ];
//        // 扣款顺序，秒杀款>特惠款
//        if($order['order_total_price'] <= $order['user_first_balance']){
//            $update_price['user_first_balance'] = $order['user_first_balance'] - $order['order_total_price'];
//        }else{
//            $update_price['user_first_balance'] = 0;
//            $cha1 = $order['order_total_price'] - $order['user_first_balance'];
//            if($cha1 <= $order['user_huo_balance']){
//                $update_price['user_huo_balance'] = $order['user_huo_balance'] - $cha1;
//            }else{
//                $update_price['user_huo_balance'] = 0;
////                $cha2 = $cha1 - $order['user_huo_balance'];
////                $update_price['user_other_balance'] = $order['user_other_balance'] - $cha2;
////                if($cha2 <= $order['user_other_balance']){
////                    $update_price['user_other_balance'] = $order['user_other_balance'] - $cha2;
////                }else{
////                    return json(['status' => 0, 'msg' => '可用积分不足']);
////                }
//            }
//        }
//        $update_price['user_recharge_balance'] = $order['user_recharge_balance'] - $order['order_total_price'];
//
//        return $update_price;
    }

    /**
     * 特惠商品列表
     * @param $where     查询条件
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function thGoods($where = []){
        $data = Db::table('up_goods')
            ->where('goods_status', 1)
            ->where($where)
            ->field('goods_id, goods_name, goods_thumb, goods_spec, goods_stock, goods_sale_num, 
            goods_is_show_sale_num, goods_is_show_stock, goods_price, goods_vip_price, goods_first_cate')
            ->page($this->page, 10)
            ->order('goods_sort desc, goods_time desc')
            ->select();
        return $data;
    }
}